import { defineStore } from "pinia"
import store from "store2"
import { ref,computed } from "vue"
export const useWebsiteStore = defineStore('websiteStore', () => {
  // 网站列表
  const websiteList = ref([])
  // 搜索结果列表
  const searchList = ref([])
  //搜索关键字
  const searchKeywords = ref('')
  //控制添加框是否显示
  const isShow = ref(false)
  // 添加
  const addWebsite = (website) => {
    if (websiteList.value.find(item => item.url === website.url)) { // 判断是否已存在
      myApi.alert('该网站已存在')
      return
    }
    websiteList.value.unshift(website)
    store('websites', websiteList.value)
  }
  // 初始化
  const init = () => {
    websiteList.value = store('websites')
  }
  // 删除
  const deleteWebsite = (url) => {
    websiteList.value = websiteList.value.filter(item => item.url !== url)
    store('websites', websiteList.value)
  }
  // 搜索
  const find = (keywords) => {
    if (keywords) {
      searchList.value = websiteList.value.filter(item => item.title.includes(keywords));
    }
  }
  // 过滤搜索结果
  const filterWebsites = computed(() => {
    return searchKeywords.value === '' ? websiteList.value : searchList.value
  })
  //拿到搜索关键字
  const getSearchKeywords = (keywords) => {
    searchKeywords.value = keywords
  }
  //控制添加框显示或者隐藏函数
  const setIsShow = (value) => {
    isShow.value = value
  }

  return {
    websiteList,
    addWebsite,
    init,
    find,
    deleteWebsite,
    filterWebsites,
    getSearchKeywords,
    setIsShow,
    isShow
  }
})
